package com.djc.exam.webapp.base.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;


/**
 * @description: 对象转换工具类
 * @date 2019/12/29 17:24
 * @version V1.0.0
 */
@Slf4j
public class ConverterUtil {

	/**
	 * @methodName: copyProperties
	 * @description: 将src对象中的属性值复制到新建的desc对象的同名属性中
	 * @param src:
	 * @param descClass:
	 * @return: T
	 */
	public static <T> T copyProperties(Object src, Class<T> descClass) {
		T t = null;
		try {
			t = descClass.newInstance();
			BeanUtils.copyProperties(src, t);
		} catch (Exception e) {
			log.info("使用BeanUtils工具类对象类型转换异常", e);
		}
		return t;
	}

	/**
	 * @methodName: copyList
	 * @description: 将srcList中的元素复制到元素类型为descClass的List集合中
	 * @param srcList:
	 * @param descClass:
	 * @return: java.util.List<T>
	 */
	public static <T> List<T> copyList(@SuppressWarnings("rawtypes") List srcList, Class<T> descClass) {

		List<T> descList = new ArrayList<T>();
		if (srcList != null) {
			for (Object obj : srcList) {
				T t = ConverterUtil.copyProperties(obj, descClass);
				descList.add(t);
			}
		}
		return descList;
	}



	/**
	 * List<Bean> 转  List<Map>
	 * @param list
	 * @return
	 */
	public static <T> List<Map<String,Object>> listConvert(List<T> list){
		List<Map<String,Object>> list_map=new ArrayList<Map<String,Object>>();
		try {
			for (T t : list) {
				Field[] fields=getAllFields(t);
				Map<String, Object> m = new HashMap<String, Object>();
				for(Field field:fields){
					try {
						String keyName=field.getName();
						if(keyName.equals("serialVersionUID")) {
							continue;
						}
						PropertyDescriptor pd = new PropertyDescriptor(keyName,t.getClass());
						Method getMethod = pd.getReadMethod();// 获得getter方法
						Object o = getMethod.invoke(t);// 执行get方法返回一个Object
						m.put(keyName, o);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				list_map.add(m);
			}
			return list_map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取所有属性 包括父类
	 * @param object
	 * @return
	 */
	public static Field[] getAllFields(Object object){
		Class clazz = object.getClass();
		List<Field> fieldList = new ArrayList<>();
		while (clazz != null){
			fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
			clazz = clazz.getSuperclass();
		}
		Field[] fields = new Field[fieldList.size()];
		fieldList.toArray(fields);
		return fields;
	}
}
